package com.github.shiqiyue.app.config.security.sapi;


import com.github.shiqiyue.app.common.result.Result;
import com.github.shiqiyue.app.common.result.ResultMsg;
import com.github.shiqiyue.app.common.utils.ResponseUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/***
 * 后台用户登录失败处理
 * @author wenyao.wu
 */
public class SapiAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if (e instanceof BadCredentialsException) {
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.LOGIN_USERNAME_PASSWORD_ERROR)), httpServletResponse);
        } else if (e instanceof DisabledException) {
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.USER_DISABLED)), httpServletResponse);
        } else {
            ResponseUtils.populateResponse(ResponseEntity.ok(Result.fail(ResultMsg.LOGIN_USERNAME_PASSWORD_ERROR)), httpServletResponse);
        }
    }
}
